//
//  AppDelegate.m
//  one_mile_01
//
//  Created by 王雅蓉 on 15/8/21.
//  Copyright (c) 2015年 王雅蓉. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import "Reachability.h"
//微信SDK头文件
#import "WXApiManager.h"

//新浪微博SDK头文件
#import "WeiboSDK.h"
#import "LoginViewController.h"

#import <ShareSDKExtension/SSEShareHelper.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>
#import <ShareSDKUI/SSUIShareActionSheetCustomItem.h>
#import <ShareSDK/ShareSDK+Base.h>

//推送
#import <TAESDK/TAESDK.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //[self startNetWork];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self.window makeKeyAndVisible];
    
    self.mainTab = [[MainTabViewController alloc] init];
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        
        NSLog(@"第一次启动");
        self.leadPageVC = [[leadPageViewController alloc]init];
        self.window.rootViewController = self.leadPageVC;
        self.leadPageVC.myDelegate = self;
    } else {
        
        self.window.rootViewController = self.mainTab;
    }
    
//    推送
    [self registerAPNS:application :launchOptions];
    [self init_tae];
    [self registerMsgReceive];
    
//    登录
    [WXApi registerApp:@"wx9f8dd4b9cbd736a6" withDescription:@"onemile1.0"];
    
    [WeiboSDK registerApp:kAppKey];
    
    [ShareSDK registerApp:@"onemileApi"
          activePlatforms:@[@(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeWechat)]
                 onImport:^(SSDKPlatformType platformType) {
                     
                     switch (platformType)
                     {
                         case SSDKPlatformTypeWechat:
                             [ShareSDKConnector connectWeChat:[WXApi class]];
                             break;
                         case SSDKPlatformTypeSinaWeibo:
                             [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                             break;
                         default:
                             break;
                     }
                     
                 }
     
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
              
              switch (platformType)
              {
                  case SSDKPlatformTypeSinaWeibo:
                      //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                      [appInfo SSDKSetupSinaWeiboByAppKey:@"309044909"
                                                appSecret:@"adf254d903ef8f2f2a621646c0968ff6"
                                              redirectUri:@"http://www.1yingli.cn"
                                                 authType:SSDKAuthTypeBoth];
                      break;
                  case SSDKPlatformTypeWechat:
                      //设置微信应用信息
                      [appInfo SSDKSetupWeChatByAppId:@"wx9f8dd4b9cbd736a6"
                                            appSecret:@"2a43bd1763ec657e7114df63fd0af290"];
                      break;
                  case SSDKPlatformTypeQQ:
                      //设置QQ应用信息，其中authType设置为只用SSO形式授权
                      [appInfo SSDKSetupQQByAppId:@"100371282"
                                           appKey:@"aed9b0303e3ed1e27bae87c33761161d"
                                         authType:SSDKAuthTypeSSO];
                      break;
                  default:
                      break;
              }
          }];

    return YES;
}

#pragma mark -- 初始化服务
- (void) init_tae {

    [[TaeSDK sharedInstance] setDebugLogOpen:NO]; //测试
    [[TaeSDK sharedInstance] setTaeSDKEnvironment:TaeSDKEnvironmentRelease];
    [[TaeSDK sharedInstance] setCloudPushSDKOpen:TRUE]; // 一定要打开云通道
    [[TaeSDK sharedInstance] asyncInit:^{
        
        NSLog(@"======================> 初始化成功");
        NSLog(@"======================> DeviceID：%@", [CloudPushSDK getDeviceId]);
    } failedCallback:^(NSError *error) {
        
        NSLog(@"======================> 初始化失败:%@",error);
    }];
}

#pragma mark -- 注册苹果的推送
- (void) registerAPNS:(UIApplication *)application :(NSDictionary *)launchOptions {

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        // iOS 8 Notifications
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [application registerForRemoteNotifications];
    } else {
    
        // iOS < 8 Notifications
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound)];
    }
    [CloudPushSDK handleLaunching:launchOptions]; // 作为 apns 消息统计
}

#pragma mark 注册接收CloudChannel 推送下来的消息
- (void) registerMsgReceive {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReceived:) name:@"CCPDidReceiveMessageNotification" object:nil]; // 注册
}

// 推送下来的消息抵达的处理示例（上线前如果不使用消息，则不要此外代码）
- (void)onMessageReceived:(NSNotification *)notification {
    
    NSData *data = [notification object];
    NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // 报警提示
    if(![NSThread isMainThread])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"有消息抵达" message:message delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
            [alertView show];
        });
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"有消息抵达" message:message delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        [alertView show];
    }
}

#pragma mark -- 注册deviceToken
// 苹果推送服务回调，注册 deviceToken
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [CloudPushSDK registerDevice:deviceToken];
}

// 通知统计回调
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // app open
    
    NSLog(@"收到通知一条~");
    // 打印自定义参数
    NSLog(@"自定义参数为 ： %@",userInfo);
    
    self.mainTab.selectedViewController = self.mainTab.viewControllers[2];
    
    [CloudPushSDK handleReceiveRemoteNotification:userInfo];
}

//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError %@", error);
}

#pragma mark -- 消息接收接口
- (void) listenerOnChannelOpened {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChannelOpened:) name:@"CCPDidChannelConnectedSuccess" object:nil]; // 注册
}

// 推送下来的消息抵达的处理示例
- (void)onChannelOpened:(NSNotification *)notification {
    // doSomething
}

#pragma mark -- leaderPageDelegate
//点击体验方法
-(void)change{
    self.window.rootViewController = self.mainTab;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alphaNavigation" object:self];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alphaNavigation" object:self];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [[LoginViewController shareLoginHandler] weiboHandleURL:url];
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    //跳转支付宝钱包进行支付，处理支付结果
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"openURL = %@", url);
        NSLog(@"result = %@", resultDic);
    }];
    
    [[LoginViewController shareLoginHandler] weiboHandleURL:url];
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

#pragma mark -- 网络状态
-(void)startNetWork{
    
    Reachability* reach = [Reachability reachabilityWithHostname:@"leting"];
    NSLog(@"-- current status: %@", reach.currentReachabilityString);
    
    // start the notifier which will cause the reachability object to retain itself!
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    [reach startNotifier];
}
- (void) reachabilityChanged: (NSNotification*)note {
    Reachability * reach = [note object];
    NSString *str = @"";
    if(![reach isReachable])
    {
        str = @"No";
        [[NSNotificationCenter defaultCenter]postNotificationName:@"IsNetWork" object:str];
        return;
    }
    str = @"Yes";
    [[NSNotificationCenter defaultCenter]postNotificationName:@"IsNetWork" object:str];
    NSLog(@"网络可用");
    NSString *Wifi = @"";
    if (reach.isReachableViaWiFi) {
        Wifi = @"Yes";
        [[NSNotificationCenter defaultCenter]postNotificationName:@"IsWifi" object:Wifi];
        NSLog( @"当前通过wifi连接");
    } else {
        Wifi = @"No";
        [[NSNotificationCenter defaultCenter]postNotificationName:@"IsWifi" object:Wifi];
        NSLog( @"wifi未开启，不能用");
    }
    NSString *Mobile3G = @"";
    if (reach.isReachableViaWWAN) {
        Mobile3G = @"Yes";
        [[NSNotificationCenter defaultCenter]postNotificationName:@"Is3gOr2g" object:Mobile3G];
        NSLog( @"当前通过2g or 3g连接");
    } else {
        Mobile3G = @"No";
        [[NSNotificationCenter defaultCenter]postNotificationName:@"Is3gOr2g" object:Mobile3G];
        NSLog( @"2g or 3g网络未使用");
    }
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.wyr.one_mile_01" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"one_mile_01" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"one_mile_01.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
